package com.jiali.backend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiali.backend.Utils.UserServiceUtils;
import com.jiali.backend.common.ResponseResult;
import com.jiali.backend.controller.request.ReviewRequest;
import com.jiali.backend.mapper.ReviewMapper;
import com.jiali.backend.model.AppointmentOrder;
import com.jiali.backend.model.Review;
import com.jiali.backend.model.User;
import com.jiali.backend.service.AppointmentOrderService;
import com.jiali.backend.service.ReviewService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review>
        implements ReviewService {
    @Resource
    private AppointmentOrderService appointmentOrderService;
    @Resource
    private UserServiceUtils userServiceUtils;

    @Override
    @Transactional
    public ResponseResult<Review> createReview(ReviewRequest reviewRequest,
                                               HttpServletRequest request) {
        // 验证用户登录
        User currentUser = userServiceUtils.getCurrentUser(request);
        if (currentUser == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 验证订单状态
        AppointmentOrder order = appointmentOrderService.getById(reviewRequest.getOrderId());
        if (order == null) {
            return ResponseResult.fail(404, "订单不存在", null);
        }
        if (!order.getUserId().equals(currentUser.getId())) {
            return ResponseResult.fail(403, "无权评价该订单", null);
        }
        if (order.getStatus() != 2) { // 假设2表示已完成状态
            return ResponseResult.fail(400, "只有已完成订单可评价", null);
        }

        // 创建评价
        // 创建评价
        Review review = new Review();

        review.setOrderId(reviewRequest.getOrderId());
        review.setRating(reviewRequest.getRating());
        review.setComment(reviewRequest.getComment());
        review.setCreateDatetime(LocalDateTime.now());
        this.save(review);
        order.setCommentStatus(1); // 1表示已评价
        appointmentOrderService.updateById(order);
        return ResponseResult.success(200,"OK",review);
    }
    @Override
    public ResponseResult<Review> getReviewByOrderId(Integer orderId) {
        Review review = this.lambdaQuery()
                .eq(Review::getOrderId, orderId)
                .one();
        if (review == null) {
            return ResponseResult.fail(404, "未找到评论", null);
        }
        return ResponseResult.success(review);
    }
}